#include "StdAfx.h"
#include "Unit.h"
#include "UnitManager.h"



CUnit::CUnit(void):m_BeginPoint(0,0),m_EndPoint(0,0),ID(getAvailableID())
{
	m_ChildList=new CUnitVec();
	m_LinkList=new LinkVec();
}

CUnit::~CUnit(void)
{
	delete m_ChildList;
	delete m_LinkList;
}
void CUnit::AddChild(CUnit* unit)
{
	m_ChildList->insert(m_ChildList->end(),unit);
}

void CUnit::DeleteChild(CUnit* unit)
{
	CUnitItr it;
	for (it=m_ChildList->begin();it!=m_ChildList->end(); it++)
	{
		CUnit* p=*it;
		if (p->Equals(unit))
		{
			m_ChildList->erase(it);
			break;
		}
	}

}
BOOL CUnit::Equals(CUnit* unit)
{
	int count=0;
	CPoint* p=GetVertex(count);
	int unit_count=0;
	CPoint* unit_p=unit->GetVertex(unit_count);
	if(count!=unit_count)
	{
		delete p;
		delete unit_p;
		return FALSE;
	}
	else
	{
		for (int i=0;i<count;i++)
		{
			if (p[i]!=unit_p[i])
			{
				delete p;
				delete unit_p;
				return FALSE;
			}
		}
	}
	delete p;
	delete unit_p;
	return TRUE;
}
void CUnit::Save(CArchive& out)
{
	out<<ID;
	out<<m_BeginPoint;
	out<<m_EndPoint;
	
	out<<(int)m_ChildList->size();
	for (CUnitItr it=m_ChildList->begin(); it!=m_ChildList->end(); it++)
	{
		(*it)->Save(out);
	}
}
void CUnit::Load(CArchive& in)
{
	in>>ID;
	in>>m_BeginPoint;
	in>>m_EndPoint;

	int size;
	in>>size;
	for (int i=0; i<size; i++)
	{
		CUnit* unit=unitFactory(in);
		AddChild(unit);
		unit->Load(in);
	}
}
